<template>
	<view class="pages-user-login" v-if="isLoad">
		<view class="flex-center flex-column" style="height: 100vh">
			<block v-if="!configInfo.plugAuth.coachport">
				<abnor type="NOT_AUTH" :isCenter="true"></abnor>
			</block>
			<block v-if="configInfo.plugAuth.coachport">
				<image mode="aspectFill" lazy-load class="logo-img radius-26 mb-md" :src="configInfo.app_logo"></image>
				<view class="f-caption c-caption">{{configInfo.coach_app_text || configInfo.app_text}}</view>
				<view style="height: 80rpx;"></view>
				<view @tap.stop="toChooseLogin('weixin')" class="login-btn wechat flex-center f-title c-base radius"
					:style="{ background: primaryColor}"><i class="iconfont icon-weixin mr-md"></i>微信登录 </view>
				<!-- #ifdef APP-PLUS -->
				<view @tap.stop="toChooseLogin('apple')" class="login-btn apple flex-center f-title c-black radius"
					v-if="is_ios_login"><i class="iconfont icon-apple mr-sm"></i>Sign in with Apple
				</view>
				<!-- #endif -->
			<!-- <view @tap.stop="toAccountLogin" class="login-btn phone flex-center f-title c-base radius" :style="{
			borderColor: primaryColor,color:primaryColor}"><i class="iconfont iconshoujitianchong mr-md"></i>账号登录
			</view> -->
				<view @tap.stop="isAgree=!isAgree" class="flex-warp mt-lg pt-md" style="width: 220pt;"> <i
						class="iconfont mr-sm" :class="[ { 'icon-xuanze-fill': isAgree }, { 'icon-xuanze': !isAgree } ]"
						:style="{color:isAgree?primaryColor:''}"></i>
					<view class="f-caption flex-1" style="color: #6C727F;">我已详细阅读并同意<span
							@tap.stop="$util.goUrl({url:`/user/pages/protocol`})" :style="{color:primaryColor}">
							《隐私政策》 </span>与<span @tap.stop="$util.goUrl({url:`/user/pages/information`})"
							:style="{color:primaryColor}"> 《服务协议》 </span> </view>
				</view>
				<view style="height: 120rpx;"></view>
				<!-- #ifdef MP-WEIXIN-COACH -->
				<view class="f-caption c-warning fix" style="width:calc(100% - 60rpx);bottom:30rpx">
					{{detail.coach_login_text}}
					<view class="space-safe"></view>
				</view>
				<!-- #endif -->
			</block>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	import siteInfo from '@/siteinfo.js';
	export default {
		components: {},
		data() {
			return {
				isLoad: false,
				detail: {},
				is_ios_login: false,
				isAgree: false,
				lockTap: false
			}
		},
		async onLoad(options) {
			// #ifdef APP-PLUS
			let {
				browserVersion
			} = uni.getSystemInfoSync()
			let {
				platform
			} = uni.getDeviceInfo()
			this.is_ios_login = platform === 'ios' && browserVersion.split('.')[0] * 1 > 12
			// #endif
			await this.getConfigInfo()
			this.detail = await this.$api.base.getConfig()
			let {
				userInfo
			} = this
			if (!this.isLoad && (!userInfo || (userInfo && !userInfo.id))) {
				this.updateUserItem({
					key: 'isGzhLogin',
					val: false
				})
			}
			this.lockTap = false
			this.isLoad = true
			// #ifdef H5
			this.$jweixin.initJssdk(() => {
				this.toAppShare()
			})
			// #endif
		},
		onShareAppMessage() {
			return {
				title: '登录',
				imageUrl: '',
				path: `/technician/pages/login`
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			pageArr: state => state.config.pageArr,
			appLogin: state => state.user.appLogin,
			loginType: state => state.user.loginType,
			loginPage: state => state.user.loginPage,
		}),
		methods: {
			...mapActions(['getConfigInfo']),
			...mapMutations(['updateUserItem']),
			toAccountLogin() {
				if (!this.isAgree) {
					this.$util.showToast({
						title: `请先阅读并同意《隐私政策》与《服务协议》`
					})
					return
				}
				this.$util.goUrl({
					url: `/technician/pages/account/login`
				})
			},
			toChooseLogin(type) {
				this.updateUserItem({
					key: 'loginType',
					val: type
				})
				this.lockTap = false
				this.toConfirm()
			},
			toConfirm() {
				if (!this.isAgree) {
					this.$util.showToast({
						title: `请先阅读并同意《隐私政策》与《服务协议》`
					})
					return
				}
				if (this.lockTap) return
				this.lockTap = true
				// #ifdef H5
				this.toGzhLogin()
				// #endif	
				// #ifndef H5
				this.toAppLogin()
				// #endif
			},
			// 公众号登录
			async toGzhLogin() {
				let {
					siteroot,
					gzh_appid
				} = siteInfo

				this.updateUserItem({
					key: 'isGzhLogin',
					val: true
				})
				this.updateUserItem({
					key: 'commonOptions',
					val: this.commonOptions
				})

				let {
					coachInfo,
					loginPage
				} = this

				// let pageUrl = loginPage || `/pages/coach-index`
				let page = `/pages/coach-index`
				console.log(coachInfo, loginPage, page, "====coachInfo=loginPage=page")
				if (coachInfo && coachInfo.id && coachInfo.id != -1) {
					this.$util.goUrl({
						url: page,
						openType: `reLaunch`
					})
					return
				}
				this.updateUserItem({
					key: 'autograph',
					val: ''
				})

				let coachport = ''
				// #ifdef H5-COACH
				coachport = 'coach/'
				// #endif 
				let url = siteroot.split('/index.php')[0]
				let href = `${url}/${coachport}${this.portName}/?#${page}`
				let pageUrl = window.location.href;
				let redirect_uri = encodeURIComponent(href)
				let authUrl =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${gzh_appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
				window.location.href = authUrl

			},
			// 小程序、APP登录
			async toAppLogin() {
				let {
					loginType: provider
				} = this

				try {
					let [providerErr, providerData] = await uni.getProvider({
						service: 'oauth',
					});
					if (providerErr) {
						this.$util.showToast({
							title: providerErr.errMsg
						})
						this.lockTap = false
						return
					}
					let [loginErr, loginData] = await uni.login({
						provider
					})
					if (loginErr) {
						this.$util.showToast({
							title: loginErr.errMsg
						})
						this.lockTap = false
						return
					}
					// #ifdef MP-WEIXIN
					let pid = 0
					let coupon_atv_id = 0
					let pageUrl = this.loginPage || `/pages/coach-index`
					if (pageUrl.includes('pid=')) {
						pid = pageUrl.split('pid=')[1].split('&')[0]
					}
					if (pageUrl.includes('coupon_atv_id=')) {
						pid = pageUrl.split('coupon_atv_id=')[1].split('&')[0]
					}
					let userInfo = {
						code: loginData.code,
						pid,
						coupon_atv_id
					}
					// #endif
					// #ifdef APP-PLUS
					let [infoErr, infoData] = await uni.getUserInfo({
						provider
					})
					if (infoErr) {
						this.$util.showToast({
							title: infoErr.errMsg
						})
						this.lockTap = false
						return
					}
					let {
						userInfo = {}
					} = infoData
					let {
						openId = ''
					} = userInfo
					if (!openId) {
						this.lockTap = false
						return
					}
					// #endif

					this.$util.showLoading({
						title: "登录中..."
					})
					try {
						let param = {
							// #ifdef MP-WEIXIN
							type: 1,
							// #endif
							// #ifndef MP-WEIXIN
							type: provider == 'weixin' ? 2 : 3,
							// #endif
							param: {
								data: userInfo
							},
							init: 1
						}
						this.toConfirmLogin(param)
					} catch (e) {
						this.$util.hideAll()
						this.lockTap = false
					}
				} catch (e) {
					this.$util.showToast({
						title: `没有获取到用户信息，请确认已登录`
					})
					this.lockTap = false
				}
			},
			async toConfirmLogin(login_params) {
				let {
					loginType
				} = this

				let {
					type,
					param,
					init = 0
				} = login_params

				// #ifdef MP-WEIXIN
				param = param.data
				// #endif

				// #ifdef MP-WEIXIN-COACH
				param.is_coach = 1
				// #endif

				// #ifdef APP-PLUS
				if (this.is_app_user == 2) {
					param.is_coach = 1
				}
				// #endif

				let methodType = {
					1: 'login',
					2: 'appLogin',
					3: 'iosLogin'
				}
				let methodModel = methodType[type]
				let user_info = await this.$api.base[methodModel](param)
				// #ifdef APP-PLUS
				if (init == 1) {
					this.updateUserItem({
						key: 'appLogin',
						val: param.data
					})
				}
				// #endif

				let {
					autograph,
					coach_status,
					data
				} = user_info

				this.$util.hideAll()
				// #ifdef MP-WEIXIN-COACH
				if (![2, 3].includes(coach_status)) {
					this.$util.showToast({
						title: `您不是内部人员，不能登录哦！`
					})
					return
				}
				// #endif
				this.updateUserItem({
					key: 'isShowLogin',
					val: false
				})
				this.updateUserItem({
					key: 'userInfo',
					val: data
				})
				this.updateUserItem({
					key: 'autograph',
					val: autograph
				})
				this.$util.back()
				let url = this.loginPage || `/pages/coach-index`
				this.$util.goUrl({
					url,
					openType: `reLaunch`
				})
			},
			toAppShare() {
				let {
					siteroot
				} = siteInfo
				let url = siteroot.split('/index.php')[0]
				let port = ''
				// #ifdef H5-COACH
				port = 'coach/'
				// #endif
				// #ifdef APP-PLUS
				port = this.is_app_user == 1 ? '' : 'coach/'
				// #endif
				let href = `${url}/${port}${this.portName}/?#/technician/pages/login`
				let title = '登录'
				let summary = ''
				let imageUrl = ''
				// #ifdef H5
				this.$jweixin.showOptionMenu()
				this.$jweixin.shareAppMessage(title, summary, href, imageUrl)
				this.$jweixin.shareTimelineMessage(title, href, imageUrl)
				// #endif
				// #ifdef APP-PLUS
				uni.share({
					provider: "weixin",
					scene: 'WXSceneSession',
					type: 0,
					href,
					title,
					summary,
					imageUrl,
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
				// #endif
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #fff;
		height: 100%;
	}

	.pages-user-login {


		.logo-img {
			width: 160rpx;
			height: 160rpx;
		}



		.login-btn {
			width: 220pt;
			height: 44pt;
			font-size: 13pt;
			border: 1rpx solid #000;
			transform: rotateZ(360deg);
			margin-top: 40rpx;

			.iconfont {
				font-size: 19pt;
			}
		}

		.wechat {
			border: none;
			box-shadow: 0 18rpx 9rpx 0 rgba(0, 188, 82, 0.07);
		}

		.apple {
			font-size: 15pt;
		}

		.banner-info {
			width: 100%;

			.banner-img {
				width: 100%;
				height: 100%;
			}

			.swiper-to-home {
				width: 122rpx;
				height: 47rpx;
				z-index: 999;
				right: 40rpx;
				top: 80rpx;
				background: rgba(0, 0, 0, 0.3);
			}
		}
	}
</style>